import request from "@/utils/request.js";
import {elMessageTip} from "@/utils/MessageTipUtils.js";
import {post} from "@/utils/http.js";
import {resolvePromise_status} from "@/utils/ReturnUtils.js";
import {desDecrypt, genDesKey, rsaPubEncrypt} from "@/utils/EncryptUtils.js";
import useAccountStore from "@/store/modules/AccountStore.js";

/**
 * 获取邮箱验证码
 *
 * @param mail
 * @param url
 * @param account
 * @returns {Promise<axios.AxiosResponse<any>>}
 */
export const getMailCodeAPI = (mail, url = '/login/mail/code', account = null) => {
    return request.get(
        url,
        {
            params: {
                mail: rsaPubEncrypt(mail),
                account: account === null ? null : rsaPubEncrypt(account)
            }
        }
    ).then(
        res => {
            elMessageTip(res)
            return resolvePromise_status(res)
        }
    )
}

/**
 * 邮箱登录
 *
 * @param mail
 * @param code
 * @returns {Promise<axios.AxiosResponse<*>>}
 */
export const loginByMailAPI = (mail, code) => {
    const desKey = genDesKey()
    return post(
        '/login/mail',
        {
            desKey: rsaPubEncrypt(desKey),
            mail: rsaPubEncrypt(mail),
            code: rsaPubEncrypt(code)
        }
    ).then(
        res => {
            res = desDecrypt(res, desKey)
            elMessageTip(res)
            // 登录成功，保存信息
            if (res.status) {
                const accountStore = useAccountStore();
                accountStore.saveAccount(res.data.account)
                accountStore.saveUser(res.data)
            }
            return resolvePromise_status(res)
        }
    )
}

export const loginByPwdAPI = (account, pwd) => {
    const desKey = genDesKey()
    return post(
        '/login/pwd',
        {
            desKey: rsaPubEncrypt(desKey),
            account: rsaPubEncrypt(account),
            pwd: rsaPubEncrypt(pwd)
        }
    ).then(
        res => {
            res = desDecrypt(res, desKey)
            elMessageTip(res)
            // 登录成功，保存信息
            if (res.status) {
                const accountStore = useAccountStore();
                accountStore.saveAccount(res.data.account)
                accountStore.saveUser(res.data)
            }
            return resolvePromise_status(res)
        }
    )
}

/**
 * 登录是否有效
 *
 * @returns {Promise<axios.AxiosResponse<any>>}
 */
export const loginEffectiveAPI = () => {
    return request.get(
        '/login/effective',
        {
            params: {
                account: rsaPubEncrypt(useAccountStore().account),
            }
        }
    ).then(
        res => {
            // elMessageTip(res)
            return resolvePromise_status(res)
        }
    )
}